package com.ruoyi.common.utils;

import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;

public class IdCardUtils {

    /**
     * 解析身份证号获取年龄和性别
     * @param idCard 身份证号（支持15/18位）
     * @return 包含年龄和性别的对象
     */
    public static PersonInfo parseIdCard(String idCard) {
        if (idCard == null || (idCard.length() != 15 && idCard.length() != 18)) {
            throw new IllegalArgumentException("无效的身份证号");
        }

        // 解析出生日期
        String birthDateStr = parseBirthDate(idCard);
        LocalDate birthDate = LocalDate.parse(birthDateStr, DateTimeFormatter.BASIC_ISO_DATE);

        // 计算年龄
        int age = Period.between(birthDate, LocalDate.now()).getYears();

        // 修正未过生日的情况
        if (LocalDate.now().getMonthValue() < birthDate.getMonthValue() ||
           (LocalDate.now().getMonthValue() == birthDate.getMonthValue() &&
            LocalDate.now().getDayOfMonth() < birthDate.getDayOfMonth())) {
            age--;
        }

        // 解析性别
        String gender = parseGender(idCard);
        PersonInfo personInfo = new PersonInfo(age, gender);
        personInfo.setAge(age);
        personInfo.setGender(gender);
        return personInfo;
    }

    private static String parseBirthDate(String idCard) {
        if (idCard.length() == 18) {
            return idCard.substring(6, 14); // 18位取7-14位
        } else {
            return "19" + idCard.substring(6, 12); // 15位补全年份
        }
    }

    private static String parseGender(String idCard) {
        int genderCode;
        if (idCard.length() == 18) {
            genderCode = Character.getNumericValue(idCard.charAt(16)); // 第17位
        } else {
            genderCode = Character.getNumericValue(idCard.charAt(14)); // 第15位
        }
        return (genderCode % 2 == 1) ? "男" : "女";
    }

    public static class PersonInfo {
        private int age;
        private String gender;

        public PersonInfo(int age, String gender) {
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }

        public String getGender() {
            return gender;
        }

        public void setGender(String gender) {
            this.gender = gender;
        }

        @Override
        public String toString() {
            return "PersonInfo{" +
                    "age=" + age +
                    ", gender='" + gender + '\'' +
                    '}';
        }

        // 构造函数、Getter方法略
    }

    public static void main(String[] args) {
        PersonInfo personInfo = parseIdCard("500109199606279619");
        System.out.println(personInfo);
    }
}
